package com.ddgame.admob;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;

import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.coregraphics.CGSize;
import org.robovm.apple.foundation.NSArray;
import org.robovm.apple.foundation.NSString;
import org.robovm.apple.foundation.NSURL;
import org.robovm.apple.uikit.UIActivityViewController;
import org.robovm.apple.uikit.UIDevice;
import org.robovm.apple.uikit.UIPopoverArrowDirection;
import org.robovm.apple.uikit.UIPopoverController;
import org.robovm.apple.uikit.UIScreen;
import org.robovm.apple.uikit.UIUserInterfaceIdiom;
import org.robovm.apple.uikit.UIViewController;
import org.robovm.pods.google.mobileads.GADAdSize;
import org.robovm.pods.google.mobileads.GADBannerView;
import org.robovm.pods.google.mobileads.GADInterstitial;
import org.robovm.pods.google.mobileads.GADInterstitialDelegateAdapter;
import org.robovm.pods.google.mobileads.GADRequest;
import org.robovm.pods.google.mobileads.GADRewardBasedVideoAd;
import org.robovm.pods.google.mobileads.GADRewardBasedVideoAdDelegateAdapter;

import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by dennieschen on 2017/1/3.
 */

public class AdmobADManager {
    public static String AD_BANNER_UNIT_ID = "ca-app-pub-8282524211241560/6139555730";
    public static String AD_INTERS_UNIT_ID = "ca-app-pub-8282524211241560/7616288936";
    public static String AD_LAUNCH_UNIT_ID = "ca-app-pub-8282524211241560/7616288936";
    public static String AD_REWARD_UNIT_ID = "ca-app-pub-8282524211241560/5074291148";
    public static String APP_URL = "itms-apps://itunes.apple.com/app/id1140422640";
    public static String shareContentEN = "Popular around the world to the casual puzzle game－Checker1010+，go to app store search 'Checker1010+'，Or jump through the link to find！";
    public static String shareContentZH = "风靡全球到休闲益智游戏－方格1010+，到app store搜索“方格1010+”，或者通过这个链接可以找到哦！";

    private GADBannerView mBanner;
    private GADInterstitial mInterAD;
    private GADRewardBasedVideoAd mGADRewardBasedVideoAd;
    private GADRewardBasedVideoAdDelegateAdapter mGADRewardBasedVideoAdDelegate;

    private static AdmobADManager mInstance;

    private static boolean isInterTimeOut = false;
    private AdmobADManager(){

//        Timer.instance().scheduleTask(new Timer.Task() {
//            @Override
//            public void run() {
//                AdmobADManager.isInterTimeOut = true;
//            }
//        }, 0, 15 * 1000);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("------ isInterTimeOut -----");
                AdmobADManager.isInterTimeOut = true;
            }
        }, 0, 20 * 1000);
    }


    public static AdmobADManager getmInstance() {
        if(mInstance == null) {
            mInstance = new AdmobADManager();
        }
        return mInstance;
    }

    public void initBanner(){
        UIViewController controller = ((IOSApplication) Gdx.app).getUIViewController();
//        CGSize screenSize = UIScreen.mainScreen().bounds().size();
//        String model = UIDevice.currentDevice().model();
//        System.out.println("model=" + model);
//        int adHeight = "iPad".equals(model) ? 90 : 50;
//        mBanner = GADBannerView.alloc().initWithAdSizeOrigin(GoogleMobileAds.kGADAdSizeSmartBannerPortrait(),
//                new CGPoint(0, screenSize.height() - adHeight));

        boolean isLandscape = isLandscape();
        if(isIphonex()) {
            mBanner = new GADBannerView();
            mBanner.setAdSize(isLandscape ? GADAdSize.SmartBannerLandscape() : GADAdSize.SmartBannerPortrait());
            setBannerPosition(2);
        } else {
            mBanner = new GADBannerView();
            mBanner.setAdSize(isLandscape ? GADAdSize.SmartBannerLandscape() : GADAdSize.SmartBannerPortrait());
        }

        mBanner.setRootViewController(controller);
        mBanner.setAdUnitID(AD_BANNER_UNIT_ID);

        System.out.println("initBanner now");
        GADRequest request = new GADRequest();
        mBanner.loadRequest(request);
        controller.getView().addSubview(mBanner);
    }

    private boolean isLandscape(){
        CGSize screenSize = UIScreen.getMainScreen().getBounds().getSize();
        return screenSize.getWidth() > screenSize.getHeight();
//        return UIApplication.getSharedApplication().getStatusBarOrientation().equals(UIDeviceOrientation.LandscapeLeft)||
//                UIApplication.getSharedApplication().getStatusBarOrientation().equals(UIDeviceOrientation.LandscapeRight);

    }

    public static boolean isIphonex(){
        CGSize screenSize = UIScreen.getMainScreen().getBounds().getSize();
        return (screenSize.getWidth() / screenSize.getHeight()) < 1200f / 2436f;
    }

    public void showBanner(){
        if(mBanner != null) {
            mBanner.setHidden(false);
        }
    }

    public void dismissBanner(){
        if(mBanner != null) {
            mBanner.setHidden(true);
        }
    }

    public boolean bannerIsHidden(){
        if(mBanner != null) {
            return mBanner.isHidden();
        }
        return true;
    }

    public boolean bannerLoaded(){
        return mBanner != null;
    }

    /**
     *
     * @param position
     * 0=top
     * 1=bottom
     */
    public void setBannerPosition(int position) {
        if(null == mBanner) {
            return;
        }

        CGRect rect = mBanner.getFrame();
        CGSize screenSize = UIScreen.getMainScreen().getBounds().getSize();
        double screenWidth = screenSize.getWidth();
        double screenHeight = screenSize.getHeight();
        double bannerWidth = rect.getWidth();
        double bannerHeight = rect.getHeight();
        double bannerX = 0;
        double bannerY = 0;
        switch (position) {
            case 0:
                bannerX = (screenWidth - bannerWidth) / 2;
                bannerY = 0;
                break;
            case 1:
                bannerX = (screenWidth - bannerWidth) / 2;
                bannerY = screenHeight - bannerHeight;
                break;
            case 2:
                bannerX = (screenWidth - bannerWidth) / 2;
                bannerY = 42;
                break;
        }
        rect.setX(bannerX);
        rect.setY(bannerY);
        mBanner.setFrame(rect);
    }

    private GADInterstitialDelegateAdapter intersDelegate;
    public void setIntersDelegate(GADInterstitialDelegateAdapter delegate){
        this.intersDelegate = delegate;
    }

    public void initInterAd(){
        System.out.println("initInterAd now");
        mInterAD = new GADInterstitial(AD_INTERS_UNIT_ID);
        GADRequest requestInterstitial = new GADRequest();
        if(this.intersDelegate != null) {
            mInterAD.setDelegate(this.intersDelegate);
        }
        mInterAD.loadRequest(requestInterstitial);
    }


    public void showInterAd(){
        System.out.println("showInterAd isReady=" + mInterAD.isReady());
        if (mInterAD != null && mInterAD.isReady()) {
            mInterAD.present(((IOSApplication) Gdx.app).getUIViewController());
            initInterAd();
            AdmobADManager.isInterTimeOut = false;
        }
    }

    public boolean isInterReady(){
        return mInterAD != null && mInterAD.isReady() && AdmobADManager.isInterTimeOut;
    }

    public boolean rewardReady(){
        return mGADRewardBasedVideoAd != null && mGADRewardBasedVideoAd.isReady();
    }

    public void initRewardAd(){
        System.out.println("initRewardAd now");
        mGADRewardBasedVideoAd = new GADRewardBasedVideoAd();
        GADRequest request = new GADRequest();
        if(mGADRewardBasedVideoAdDelegate != null) {
            mGADRewardBasedVideoAd.setDelegate(mGADRewardBasedVideoAdDelegate);
        }
        mGADRewardBasedVideoAd.loadRequest(request, AD_REWARD_UNIT_ID);
    }

    public void showRewardAd(){
        System.out.println("showRewardAd isReady=" + mGADRewardBasedVideoAd.isReady());
        if (mGADRewardBasedVideoAd != null && mGADRewardBasedVideoAd.isReady()) {
            mGADRewardBasedVideoAd.present(((IOSApplication) Gdx.app).getUIViewController());
            initRewardAd();
        }
    }

    public void setmGADRewardBasedVideoAdDelegate(GADRewardBasedVideoAdDelegateAdapter mGADRewardBasedVideoAdDelegate) {
        this.mGADRewardBasedVideoAdDelegate = mGADRewardBasedVideoAdDelegate;
        if(mGADRewardBasedVideoAd != null) {
            mGADRewardBasedVideoAd.setDelegate(mGADRewardBasedVideoAdDelegate);
        }
    }

    public void share(String language) {
        try {
            UIViewController controller = ((IOSApplication) Gdx.app).getUIViewController();
            NSString extToShare = new NSString(language.startsWith("zh") ? shareContentZH : shareContentEN);
            NSURL urlToShare = new NSURL(APP_URL);
            NSArray activityItems = new NSArray(extToShare, urlToShare);
            UIActivityViewController activityVC = new UIActivityViewController(activityItems, null);


            if (UIDevice.getCurrentDevice().getUserInterfaceIdiom() == UIUserInterfaceIdiom.Phone) {
                controller.presentViewController(activityVC, true, null);
            } else {
                UIPopoverController popUp = new UIPopoverController(activityVC);
                popUp.presentFromRectInView(CGRect.Zero(), controller.getView(), UIPopoverArrowDirection.Any, true);
            }
        } catch (Exception e) {
            System.out.println("share is error=" + e.toString());
        }

    }
}
